import React, { useContext } from "react";

const appContext = React.createContext(null);

const User = () => {
    const contextValue = useContext(appContext);
    return (
        <div>
            User: {contextValue.appState.user.name}
        </div>
    );
}

// reduce 用于规范 state 创建流程的函数
const reducer = (state, {type, payload = {}}) => {
    if (type === 'updateUser') {
        return {
            ...state,
            user: {
                ...state.user,
                ...payload
            }
        }
    } else {
        return state;
    }
}

const UserModifier = () => {
    const { appState, setAppState } = useContext(appContext);
    const changeHandler = (e) => {
        const newState = reducer(appState, {
            type: 'updateUser',
            payload: {
                name: e.target.value
            }
        })

        setAppState(newState);
    }
    return (
        <div>
            <input type="text" value={appState.user.name} onChange={changeHandler}/>
        </div>
    );
}

const A = () => <section>A 组件<User/></section>;
const B = () => <section>B 组件<UserModifier/></section>;
const C = () => <section>C 组件</section>;

function App() {

    const [appState, setAppState] = React.useState({
        user: {
            name: 'tom',
            age: 99
        }
    });
    const contextValues = { appState, setAppState };

    return (
        <appContext.Provider value={contextValues}>
            <A/>
            <B/>
            <C/>
        </appContext.Provider>
    );
}

export default App;